# set working directory
setwd('~/replication_files')

# function to load and install packages
load_packages<-function(packages){
  sapply(packages,function(x){
    f<-require(x,character.only=T)
    if(!f) install.packages(x); f<-require(x,character.only=T)
    return(f)},USE.NAMES=T)
}

# load packages
load_packages(c('data.table'))

# read data
(tabDTfull<-readRDS('Table1.rds'))

# transpose data
(tabDTfull<-t(tabDTfull[,!'Data_Name',with=F]))
# paste columns together
(tabDTfull<-apply(tabDTfull,1,paste,collapse=' & '))
# add variable info
(tabDTfull<-paste(c('Male','College','White','Has child','Democrat','Republican','Median age','N'),
                  tabDTfull,sep=' & '))
# add ending line
(tabDTfull<-paste(tabDTfull,'\\\\'))
# add a horizontal line
tabDTfull[7]<-paste(tabDTfull[7],'\\midrule')
tabDTfull

# create top and bottom of latex table
tab_top<-c('\\begin{table}[ht]',
           '\\begin{footnotesize}',
           '\\begin{center}',
           '\\caption{Participant demographics by sample}',
           '\\begin{tabular}{l *{10}{c} }',
           '\\toprule',
           '& Oct./Nov. & Oct./Nov. & June/July  & July/Aug. & Oct./Nov.  & Nov.--Jan. & Jan.--March & Full & Web & Vaccine \\\\',
           '& 2016 &  2017 & 2018 & 2018 &  2018 &  2018 &  2019 & sample & data & attitudes \\\\',
           '\\midrule')
tab_bot<-c('\\midrule',
           '\\multicolumn{10}{l}{\\emph{Dates of data collection}} \\\\',
           'Surveys & 10/21--10/31& 11/2--11/8& 6/25--7/24& 7/26--7/30& 10/19--10/24& 11/20--12/28& 2/6--2/25& & & \\\\',
           'Web data & 10/7--11/14& 10/25--11/22& 6/11--7/31& 7/12--8/2& 10/5--11/5& 11/12--1/16& 1/24--3/11&  & &  \\\\',
           '\\bottomrule',
           '\\end{tabular}',
           '\\end{center}',
           '\\end{footnotesize}',
           '\\begin{footnotesize}',
           'All population proportions are calculated using sample weights except for age.',
           'Partisan statistics do not include respondents who report leaning toward one party.',
           'Vaccine attitudes data include only responses for which corresponding behavioral data is available.',
           '\\end{footnotesize}',
           '\\label{table:tab1}',
           '\\end{table}')

# put pieces of Latex table together
(tab_fin<-c(tab_top,tabDTfull,tab_bot))
# save file
writeLines(tab_fin,'Table1.tex')
